package cn.bopomo.dealer.base.action;


import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.LookupDispatchAction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import cn.bopomo.dealer.base.common.CommonConstant;
import cn.bopomo.dealer.base.common.ServiceConfig;
import cn.bopomo.dealer.base.exception.SystemException;
import cn.bopomo.dealer.base.service.IOperatorService;
import cn.bopomo.dealer.base.util.ResultCodeDescHandler;
import cn.bopomo.dealer.base.vo.AuthorizeList;
import cn.bopomo.dealer.base.vo.ModuleList;

public class BaseAction extends LookupDispatchAction {

	protected final String S = "success";
	protected final String F = "failure";
	
	protected String codeDescXMLPath = "/WEB-INF/code_description.xml";
	
	protected Log log = LogFactory.getLog(this.getClass());

    /**
     * findFailure
     * 
     * @param mapping
     *            ActionMapping
     * @return ActionForward
     */

    protected ActionForward findFailure(ActionMapping mapping) {
        return (mapping.findForward("failure"));
    }

    /**
     * findSuccess
     * 
     * @param mapping
     *            ActionMapping
     * @return ActionForward
     */
    protected ActionForward findSuccess(ActionMapping mapping) {
        return (mapping.findForward("success"));
    }

    /**
     * removeFormBean
     * 
     * @param mapping
     *            ActionMapping
     * @param request
     *            HttpServletRequest
     */
    protected void removeFormBean(ActionMapping mapping, HttpServletRequest request) {

        // Remove the obsolete form bean
        if (mapping.getAttribute() != null) {
            if ("request".equals(mapping.getScope())) {
                request.removeAttribute(mapping.getAttribute());
            } else {
                HttpSession session = request.getSession();
                session.removeAttribute(mapping.getAttribute());
            }
        }
    }

    /**
     * addError
     * 
     * @param ex
     *            String
     * @return ActionErrors
     */
    protected ActionErrors addError(String ex) {
        ActionErrors errors = new ActionErrors();
        ActionError error = new ActionError(ex);
        errors.add(ActionErrors.GLOBAL_ERROR, error);
        return errors;
    }

    /**
     * addMessage
     * 
     * @param msg
     *            String
     * @return ActionMessages
     */
    protected ActionMessages addMessage(String msg) {
        ActionMessages msgs = new ActionMessages();
        ActionMessage mg = new ActionMessage(msg);
        msgs.add(ActionMessages.GLOBAL_MESSAGE, mg);
        return msgs;
    }

    /**
     * checkToken
     * 
     * @param HttpServletRequest
     *            request
     * @return boolean
     */
    protected boolean isVaildateToken(HttpServletRequest request) {
        boolean validate = false;
        if (!isTokenValid(request)) {
            this.saveErrors(request, this.addError("error.invalidate.token"));
            saveToken(request);
        } else {
            resetToken(request);
            validate = true;
        }

        return validate;
    }

    /**
     * isValidateCheckCode
     * 
     * @param HttpServletRequest
     *            request
     * @return boolean
     */
    protected boolean isValidateCheckCode(HttpServletRequest request) {
        boolean validate = true;
        String sessionCheckCode = String.valueOf(request.getSession().getAttribute("checkCode"));
        request.getSession().removeAttribute("checkCode");
        String checkCode = request.getParameter("checkCode");
        if (checkCode == null || checkCode.equals("") || !checkCode.equals(sessionCheckCode)) {
            saveErrors(request, addError("error.checkCode"));
            validate = false;
        }
        return validate;
    }

    /**
     * findService
     * 
     * @param String
     *            serviceName
     * @return findService
     */
    protected Object findService(String serviceName) throws Exception {
        ServletContext servletContext = servlet.getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        Object service = wac.getBean(serviceName);
        if (service == null) {
            throw new Exception("no such service named " + serviceName);
        }
        return service;

    }

    /**
     * formatMessage
     * 
     * @param String
     *            sourceName
     * @param String
     *            message
     * @param String[]
     *            subMessages
     * @return String
     */
    protected String formatMessage(String sourceName, String message, String[] subMessages) throws Exception {
        ResourceBundle bundle = ResourceBundle.getBundle(sourceName);
        String requiredFieldMsg = bundle.getString(message);
        String formattedMsg = MessageFormat.format(requiredFieldMsg, subMessages);
        return formattedMsg;
    }

    /**
     * findMessageByKey
     * 
     * @param String
     *            sourceName
     * @param String
     *            key
     * @return String
     */
    protected String findMessageByKey(String suorceName, String key) throws Exception {
        ResourceBundle bundle = ResourceBundle.getBundle(suorceName);
        String msg = bundle.getString(key);
        return msg;
    }    
    
    /**
     * getKeyMethodMap
     * 
     * @return Map
     */
    protected Map getKeyMethodMap() {
        return null;
    }

    protected String getUserId(HttpServletRequest request){
    	
    	String userId = null;
    	
    	userId = (String)request.getSession().getAttribute(CommonConstant.KEY_LOGIN_ID);
        
    	return userId;
    }
    
    
    
    protected String getUserName(HttpServletRequest request){
    	String userName = null;
    	
    	userName = (String)request.getSession().getAttribute(CommonConstant.KEY_LOGIN_NAME);
        
    	return userName;
    }
    
    protected Map getAuthorize(HttpServletRequest request){
    	Map userAuthorize = null;
    	
    	userAuthorize = (Map)request.getSession().getAttribute(CommonConstant.KEY_AUTHORIZE_MAP);
        
    	return userAuthorize;
    }
    
    protected Map getModuleAuthorize(HttpServletRequest request){
    	Map userModule = null;
    	
    	userModule = (Map)request.getSession().getAttribute(CommonConstant.KEY_MODULE_MAP);
        
    	return userModule;
    }
    
    /**
     * 检查是否有权限访问该action
     * @param request
     * @return
     */
    protected boolean hasPermission(HttpServletRequest request){
    	boolean result = false;
    	IOperatorService os = null;
    	try {
			os = (IOperatorService)this.findService(ServiceConfig.OPERATOR_SERVICE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (os == null)
			return result;
		
		String uri = request.getRequestURI();
		AuthorizeList authorize = null;
		ModuleList module = null;
		try {
			authorize = os.getAuthorizeByAction(uri);
			if (authorize == null)
				return result;
			
			module = os.getModule(authorize.getModuleList().getMid());
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map authorizeMap = this.getAuthorize(request);
		Map moduleMap = this.getModuleAuthorize(request);
		
		if (authorizeMap == null || moduleMap == null)
			return result;
		
		if (authorizeMap.containsKey(authorize.getAuthorizeTag()) && moduleMap.containsKey(module.getModuleTag())){
			result = true;
		}
    	
    	
    	return result;
    }
    
    public String getCodeDescription(String code, String configXMLPath){
    	SAXParserFactory factory = SAXParserFactory.newInstance();
	    SAXParser saxParser;
		try {
			saxParser = factory.newSAXParser();
			ResultCodeDescHandler dh = new ResultCodeDescHandler(code);
		    saxParser.parse(new File(configXMLPath), dh);
		    return dh.getDescription();
		    
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
			return "操作未成功";
		}
	    

    }
}